package question

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gfer/app/service/question"
	"github.com/gogf/gfer/app/service/reply"
	"github.com/gogf/gfer/library/response"
)

// 控制器
type C struct{}

// 问答列表
func (c *C) Index(r *ghttp.Request) {
	r.Response.WriteTplDefault(g.Map{
		"entities": question.GetList(r.GetInt("page"), 0),
	})
}

// 问答详情
func (c *C) Detail(r *ghttp.Request) {
	id := r.GetInt("id")
	if id <= 0 {
		g.Log().Panicf(`invalid id: %d`, id)
	}
	entity := question.GetDetail(id)
	r.Response.WriteTplDefault(g.Map{
		"entity": entity,
		"replies": reply.GetListContentByTid(
			reply.TypeQuestion,
			entity.Id,
			r.GetInt("page"),
		),
	})
}

// 问答保存请求
type SaveReq struct {
	Id      uint
	Title   string `v:"required#标题不能为空"`
	Content string `v:"required#内容不能为空"`
	Brief   string
	Thumb   string
	Referer string
	Tags    []string
}

// 问答保存
func (c *C) Save(r *ghttp.Request) {
	var (
		req   *SaveReq
		param *question.SaveParam
	)
	if err := r.Parse(&req); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if err := gconv.Struct(req, &param); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if len(req.Tags) > 0 {
		param.Tags = gstr.Join(req.Tags, "#")
	}
	param.Uid = r.Session.GetUint("uid")
	if err := param.Save(); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.JsonExit(r, 0, "")
}
